import { createSlice, createAsyncThunk } from '@reduxjs/toolkit';
import { borrowService } from '../../api/services/borrowService';

export interface BorrowRecord {
  id: number;
  userId: number;
  userName: string;
  materialId: number;
  materialName: string;
  borrowDate: string;
  expectedReturn: string;
  actualReturn?: string;
  status: 'borrowed' | 'returned' | 'overdue';
  purpose: string;
  createTime: string;
  updateTime: string;
}

export interface CreateBorrowRequest {
  userId: number;
  materialId: number;
  expectedReturn: string;
  purpose: string;
}

export interface UpdateBorrowRequest {
  id: number;
  expectedReturn?: string;
  actualReturn?: string;
  status?: 'borrowed' | 'returned' | 'overdue';
  purpose?: string;
}

interface BorrowState {
  borrows: BorrowRecord[];
  loading: boolean;
  error: string | null;
}

const initialState: BorrowState = {
  borrows: [],
  loading: false,
  error: null,
};

// 修正字段映射函数
const mapApiBorrowToFrontend = (apiBorrow: any): BorrowRecord => {
 return {
    id: apiBorrow.id,
    userId: apiBorrow.userid || apiBorrow.userId,
    userName: apiBorrow.username || apiBorrow.userName || '未知用户',
    materialId: apiBorrow.materialId || apiBorrow.materialID,
    materialName: apiBorrow.materialName || apiBorrow.material || '未知物资',
    borrowDate: apiBorrow.borrowDate || apiBorrow.date,
    expectedReturn: apiBorrow.expectedReturn,
    actualReturn: apiBorrow.actualReturn,
    status: (apiBorrow.status || 'borrowed') as 'borrowed' | 'returned' | 'overdue',
    purpose: apiBorrow.purpose || '',
    createTime: apiBorrow.createTime,
    updateTime: apiBorrow.updateTime,
  };
};

// 异步 thunks - 修复数据提取
export const fetchBorrows = createAsyncThunk(
  'borrow/fetchBorrows',
  async (_, { rejectWithValue }) => {
    try {
      const response = await borrowService.getBorrows();
      const data = response;
      if (!Array.isArray(data)) {
        console.error('Expected array but got:', data);
        return [];
      }

      const mappedData = data.map(mapApiBorrowToFrontend);
     return mappedData;
    } catch (error: any) {
      console.error('Fetch borrows error:', error);
      return rejectWithValue(error.response?.data?.message || error.message || '获取借用记录失败');
    }
  }
);

export const createBorrow = createAsyncThunk(
  'borrow/createBorrow',
  async (borrowData: CreateBorrowRequest, { rejectWithValue }) => {
    try {
      const requestData = {
        userid: borrowData.userId,
        materialId: borrowData.materialId,
        expectedReturn: borrowData.expectedReturn,
        purpose: borrowData.purpose,
      };
      const response = await borrowService.createBorrow(requestData);
     const data = response;
      return mapApiBorrowToFrontend(data);
    } catch (error: any) {
      console.error('Create borrow error:', error);
      return rejectWithValue(error.response?.data?.message || error.message || '创建借用记录失败');
    }
  }
);

export const updateBorrow = createAsyncThunk(
  'borrow/updateBorrow',
  async (borrowData: UpdateBorrowRequest, { rejectWithValue }) => {
    try {
      const requestData: any = {};

      if (borrowData.expectedReturn) requestData.expectedReturn = borrowData.expectedReturn;
      if (borrowData.actualReturn) requestData.actualReturn = borrowData.actualReturn;
      if (borrowData.status) requestData.status = borrowData.status;
      if (borrowData.purpose) requestData.purpose = borrowData.purpose;
      const response = await borrowService.updateBorrow(borrowData.id, requestData);
      const data = response;
      return mapApiBorrowToFrontend(data);
    } catch (error: any) {
      console.error('Update borrow error:', error);
      return rejectWithValue(error.response?.data?.message || error.message || '更新借用记录失败');
    }
  }
);

export const deleteBorrow = createAsyncThunk(
  'borrow/deleteBorrow',
  async (borrowId: number, { rejectWithValue }) => {
    try {
      await borrowService.deleteBorrow(borrowId);
      return borrowId;
    } catch (error: any) {
      console.error('Delete borrow error:', error);
      return rejectWithValue(error.response?.data?.message || error.message || '删除借用记录失败');
    }
  }
);

export const returnMaterial = createAsyncThunk(
  'borrow/returnMaterial',
  async (borrowId: number, { rejectWithValue }) => {
    try {
      const response = await borrowService.returnBorrow(borrowId);

      // 从 response.data 中获取数据
      const data = response;
      return mapApiBorrowToFrontend(data);
    } catch (error: any) {
      console.error('Return material error:', error);
      return rejectWithValue(error.response?.data?.message || error.message || '归还物资失败');
    }
  }
);

const borrowSlice = createSlice({
  name: 'borrow',
  initialState,
  reducers: {
    clearError: (state) => {
      state.error = null;
    },
  },
  extraReducers: (builder) => {
    builder
      .addCase(fetchBorrows.pending, (state) => {
        state.loading = true;
        state.error = null;
      })
      .addCase(fetchBorrows.fulfilled, (state, action) => {
        state.loading = false;
        state.borrows = action.payload;
       })
      .addCase(fetchBorrows.rejected, (state, action) => {
        state.loading = false;
        state.error = action.payload as string;
      })
      .addCase(createBorrow.pending, (state) => {
        state.loading = true;
        state.error = null;
      })
      .addCase(createBorrow.fulfilled, (state, action) => {
        state.loading = false;
        state.borrows.push(action.payload);
      })
      .addCase(createBorrow.rejected, (state, action) => {
        state.loading = false;
        state.error = action.payload as string;
      })
      .addCase(updateBorrow.pending, (state) => {
        state.loading = true;
        state.error = null;
      })
      .addCase(updateBorrow.fulfilled, (state, action) => {
        state.loading = false;
        const index = state.borrows.findIndex(b => b.id === action.payload.id);
        if (index !== -1) {
          state.borrows[index] = action.payload;
        }
      })
      .addCase(updateBorrow.rejected, (state, action) => {
        state.loading = false;
        state.error = action.payload as string;
      })
      .addCase(deleteBorrow.pending, (state) => {
        state.loading = true;
        state.error = null;
      })
      .addCase(deleteBorrow.fulfilled, (state, action) => {
        state.loading = false;
        state.borrows = state.borrows.filter(b => b.id !== action.payload);
      })
      .addCase(deleteBorrow.rejected, (state, action) => {
        state.loading = false;
        state.error = action.payload as string;
      })
      .addCase(returnMaterial.pending, (state) => {
        state.loading = true;
        state.error = null;
      })
      .addCase(returnMaterial.fulfilled, (state, action) => {
        state.loading = false;
        const index = state.borrows.findIndex(b => b.id === action.payload.id);
        if (index !== -1) {
          state.borrows[index] = action.payload;
        }
      })
      .addCase(returnMaterial.rejected, (state, action) => {
        state.loading = false;
        state.error = action.payload as string;
      });
  },
});

export const { clearError } = borrowSlice.actions;
export default borrowSlice.reducer;